<template>
	<div class="p-6">
		<!-- 操作栏 -->
		<div class="flex items-center mb-4 gap-2">
			<MultipleUpload class="ml-2" :accept="'image/*'" :limit="10" :handleUpload="handleUpload" />
		</div>

		<div>
			<el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
				批量删除
			</el-button>
		</div>

		<!-- 图片列表（修正多选） -->
		<el-checkbox-group v-model="selectedIds">
			<el-row :gutter="16">
				<el-col
					v-for="item in imageList"
					:key="item._id"
					:xs="12"
					:sm="8"
					:md="6"
					:lg="4"
					:xl="3"
					class="mb-4">
					<el-card :body-style="{ padding: '8px' }" shadow="hover">
						<div class="relative group">
							<el-checkbox class="absolute left-1 top-1 z-10" :label="item._id" />
							<img
								:src="item.url"
								class="w-full h-32 object-cover rounded cursor-pointer"
								@click="handlePreview(item)"
								:alt="item.originalName" />
							<div
								class="absolute right-1 bottom-1 flex justify-center gap-1 opacity-0 group-hover:opacity-100 transition w-full">
								<el-button
									size="small"
									type="danger"
									icon="Delete"
									circle
									@click.stop="handleDelete(item)" />
								<el-button
									size="small"
									type="info"
									icon="InfoFilled"
									circle
									@click.stop="handleInfo(item)" />
							</div>
						</div>
						<div class="mt-2 text-xs truncate text-center">{{ item.originalName }}</div>
					</el-card>
				</el-col>
			</el-row>
		</el-checkbox-group>

		<!-- 分页 -->
		<div class="flex justify-center mt-6">
			<ElsPagination
				:total="total"
				:currentPage="page"
				:pageSize="pageSize"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange" />
		</div>

		<!-- 大图预览 -->
		<els-dialog v-model="previewVisible" title="预览">
			<img :src="previewUrl" class="w-full" />
		</els-dialog>

		<!-- 文件信息 -->
		<el-dialog v-model="infoVisible" title="文件信息" width="400px">
			<el-descriptions :column="1" border>
				<el-descriptions-item label="文件名">{{ infoData.originalName }}</el-descriptions-item>
				<el-descriptions-item label="类型">{{ infoData.mimeType }}</el-descriptions-item>
				<el-descriptions-item label="大小">{{ formatSize(infoData.size) }}</el-descriptions-item>
				<el-descriptions-item label="上传时间">{{
					formatDate(infoData.uploadTime)
				}}</el-descriptions-item>
				<el-descriptions-item label="MD5">{{ infoData.md5 }}</el-descriptions-item>
				<el-descriptions-item label="URL">
					<el-link :href="infoData.url" target="_blank">{{ infoData.url }}</el-link>
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import ElsPagination from '~/components/ElsPagination/index.vue';
import MultipleUpload from '~/components/UploadCom/MultipleUpload/index.vue';

interface ImageItem {
	_id: string;
	url: string;
	originalName: string;
	mimeType: string;
	size: number;
	uploadTime: string;
	md5: string;
}

const imageList = ref<ImageItem[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);
const selectedIds = ref<string[]>([]);

const previewVisible = ref(false);
const previewUrl = ref('');
const infoVisible = ref(false);
const infoData = ref<Partial<ImageItem>>({});

function fetchList() {
	fetch(`/api/admin/file/imageList?page=${page.value}&pageSize=${pageSize.value}`)
		.then((res) => res.json())
		.then((res) => {
			if (res.code === 1) {
				imageList.value = res.data.list;
				total.value = res.data.total;
				selectedIds.value = [];
			} else {
				ElMessage.error(res.message || '获取图片失败');
			}
		});
}

function handleSizeChange(val: number) {
	pageSize.value = val;
	page.value = 1;
	fetchList();
}
function handleCurrentChange(val: number) {
	page.value = val;
	fetchList();
}

function handlePreview(item: ImageItem) {
	previewUrl.value = item.url;
	previewVisible.value = true;
}
function handleInfo(item: ImageItem) {
	infoData.value = item;
	infoVisible.value = true;
}

function handleDelete(item: ImageItem) {
	ElMessageBox.confirm('确定要删除该图片吗？', '提示', { type: 'warning' }).then(() => {
		fetch(`/api/admin/file/delete?id=${item._id}`, { method: 'DELETE' })
			.then((res) => res.json())
			.then((res) => {
				if (res.code === 1) {
					ElMessage.success('删除成功');
					fetchList();
				} else {
					ElMessage.error(res.message || '删除失败');
				}
			});
	});
}

function handleBatchDelete() {
	if (!selectedIds.value.length) return;
	ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}张图片吗？`, '批量删除', {
		type: 'warning',
	}).then(() => {
		fetch(`/api/admin/file/delete?id=${selectedIds.value.join(',')}`, {
			method: 'DELETE',
		})
			.then((res) => res.json())
			.then((res) => {
				if (res.code === 1) {
					ElMessage.success('批量删除成功');
					fetchList();
				} else {
					ElMessage.error(res.message || '批量删除失败');
				}
			});
	});
}

async function handleUpload(fileList: File[]) {
	if (!fileList.length) return;
	const formData = new FormData();
	fileList.forEach((file) => {
		formData.append('files', file);
	});
	try {
		const res = await fetch('/api/admin/file/upload', {
			method: 'POST',
			body: formData,
		});
		const data = await res.json();
		if (data.code === 1) {
			ElMessage.success('上传成功');
			fetchList();
		} else {
			ElMessage.error(data.message || '上传失败');
		}
	} catch (e) {
		ElMessage.error('上传失败');
	}
}

function formatSize(size: number = 0) {
	if (size < 1024) return size + ' B';
	if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB';
	if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(1) + ' MB';
	return (size / 1024 / 1024 / 1024).toFixed(1) + ' GB';
}
function formatDate(date: any) {
	if (!date) return '';
	return new Date(date as string).toLocaleString();
}

onMounted(fetchList);
</script>

<style scoped>
.el-card {
	transition: box-shadow 0.2s;
}
.el-card:hover {
	box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}
</style>
